import logging
from dotenv import load_dotenv
import os
from datetime import datetime


class LogConfig:
    # 静态变量，用于缓存日志实例
    _logger = None

    def __init__(self, log_file, level):
        self.log = logging.getLogger(__name__)
        self.log.setLevel(level)
        self.log_format = logging.Formatter(
            "%(asctime)s - %(filename)s:%(lineno)d - %(threadName)s- %(levelname)s - %(message)s"
        )
        # 文件处理器，将日志写入文件
        self.log_file = logging.FileHandler(log_file)
        self.log_file.setFormatter(self.log_format)

        # 控制台处理器，将日志打印到控制台
        self.log_console = logging.StreamHandler()
        self.log_console.setFormatter(self.log_format)

        # 添加处理器到日志记录器
        self.log.addHandler(self.log_file)
        self.log.addHandler(self.log_console)

        LogConfig._logger = self.log

    @staticmethod
    def get_logger():
        """
        获取日志实例。
        """
        if LogConfig._logger:
            return LogConfig._logger

        load_dotenv("../.env")
        path, name, level = (
            os.getenv("LOG_PATH", "/opt/logs/trans_flux"),
            os.getenv("LOG_FILE_NAME", "app.log"),
            os.getenv("LOG_LEVEL", "INFO"),
        )
        path = path + os.path.sep + f"{datetime.now().strftime('%Y_%m_%d')}"
        os.makedirs(path, exist_ok=True)
        log_file = os.path.join(path, name)
        return LogConfig(log_file, level)._logger
